package com.cn.sl.server.config.dialect.postgres

import org.hibernate.boot.model.FunctionContributions
import org.hibernate.dialect.PostgreSQLDialect
import org.hibernate.type.StandardBasicTypes


class CustomPostgresSQLDialect : PostgreSQLDialect() {
    override fun initializeFunctionRegistry(functionContributions: FunctionContributions?) {
        super.initializeFunctionRegistry(functionContributions)
        if (functionContributions != null) {

            val basicTypeRegistry = functionContributions.typeConfiguration.basicTypeRegistry

            // 正则匹配查询,?1：需要查询的字段，?2：正则值
            functionContributions.functionRegistry?.registerPattern(
                "regexp",
                "(?1 ~ ?2)",
                basicTypeRegistry.resolve(StandardBasicTypes.BOOLEAN)
            )

            // 全文索引查询，?1：需要查询的字段，?2：关键字
            functionContributions.functionRegistry?.registerPattern(
                "fulltext_search",
                "(?1 @@ plainto_tsquery(?2) )",
                basicTypeRegistry.resolve(StandardBasicTypes.BOOLEAN)
            )

            functionContributions.functionRegistry?.registerPattern(
                "jsonb_path_contains_single",
                "jsonb_path_contains_single(?1,?2)",
                basicTypeRegistry.resolve(StandardBasicTypes.BOOLEAN)
            )

            functionContributions.functionRegistry?.registerPattern(
                "jsonb_path_contains_all",
                "jsonb_path_contains_all(?1,string_to_array(?2, ','))",
                basicTypeRegistry.resolve(StandardBasicTypes.BOOLEAN)
            )

            functionContributions.functionRegistry?.registerPattern(
                "jsonb_path_contains_any",
                "jsonb_path_contains_any(?1,string_to_array(?2, ','))",
                basicTypeRegistry.resolve(StandardBasicTypes.BOOLEAN)
            )

            functionContributions.functionRegistry?.registerPattern(
                "jsonb_array_long_contains_single",
                "(?1::jsonb @> to_jsonb(?2))",
                basicTypeRegistry.resolve(StandardBasicTypes.BOOLEAN)
            )

            functionContributions.functionRegistry?.registerPattern(
                "jsonb_array_long_contains_all",
                "(?1::jsonb @> to_jsonb(array ?2))",
                basicTypeRegistry.resolve(StandardBasicTypes.BOOLEAN)
            )

            functionContributions.functionRegistry?.registerPattern(
                "jsonb_array_index_eq",
                "(?1::jsonb ->> ?2 = ?3)",
                basicTypeRegistry.resolve(StandardBasicTypes.BOOLEAN)
            )
        }
    }
}
